package com.coin900.coin.cmd.sop;

import com.google.gson.Gson;
import com.coin900.coin.cmd.ACmd;
import com.coin900.coin.cmd.CmdSign;
import com.coin900.coin.code.CmdCode;
import com.coin900.coin.code.RespCode;
import com.coin900.coin.persist.fu.FuUserVO;
import com.coin900.coin.persist.sop.SopRoleVO;
import com.coin900.coin.service.sop.ISopRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色新增和修改
 *
 * @author shui
 * @create 2018-01-08
 **/
@Controller
public class SopRolePutCmd extends ACmd {
    @Override
    public CmdSign execute(HttpServletRequest request, CmdSign sign) throws Exception {

        CmdSign respSign = new CmdSign(sign);
        FuUserVO user = super.getUser(sign);
        String source = sign.getSource();
        SopRoleVO sopRoleVO = new Gson().fromJson(source, SopRoleVO.class);
        Long id = sopRoleVO.getId();

        Map<String, Object> params = new HashMap<>();
        // 角色不可以重名
        String roleName = sopRoleVO.getRoleName();
        params.put("roleName", roleName);
        params.put("dataStatus", 1);
        List<SopRoleVO> dbRoleList = this.roleService.loadSopRole(params);
        if (!dbRoleList.isEmpty()) {
            respSign.setMsg("角色已经存在");
            respSign.setRespCode(RespCode.FAIL);
            return respSign;
        }

        if (id == null) {
            // 新增
            sopRoleVO.setCreatedInfor(user);
            this.roleService.insertSopRole(sopRoleVO);
        } else {
            // 修改
            params.clear();
            params.put("id", id);
            params.put("dataStatus", 1);
            List<SopRoleVO> sopRoleVOS = this.roleService.loadSopRole(params);
            if (sopRoleVOS.isEmpty()) {
                respSign.setMsg("角色不存在");
                respSign.setRespCode(RespCode.FAIL);
                return respSign;
            }
            sopRoleVO.setModifiedInfor(user);
            this.roleService.updateSopRole(sopRoleVO);
        }

        return respSign;
    }

    @Autowired
    private ISopRoleService roleService;

    @Override
    public String getCmdCode() {
        return CmdCode.SOP_ROLE_PUT;
    }
}
